// 两根线
// 同步：组件 commit -> mutations -> state
// 异步： 组件 dispatch -> actions -> commit -> mutations -> state
import { login } from '@/api/user'
import { getId, setId, setTokenC, delTokenC } from '@/utils/auth'
import { setToken, getToken, removeToken, removeName } from '@/utils/storage'
export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: {
    token: getToken(),
    userId: getId()
  },
  // 相当于组件中计算属性
  getters: {},
  // 这个是唯一修改state中数据地方
  mutations: {
    // setCount(state) {}
    setToken(state, token) {
      state.token = token
      token && setToken(token)
      token && setTokenC(token)
    },
    setId(state, userId) {
      state.userId = userId
      userId && setId(userId)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },

    removeToken (state) {
      state.token = null
      removeToken()
      delTokenC()
    },
    removeInfo(state) {
      state.userInfo = null
      removeName()
    }
  },
  // 写异步的ajax的地方
  actions: {
    // store.commit()
    // getData(store){}
    async login(store, data) {
      const res = await login(data)
      store.commit('setToken', res.token)
      store.commit('removeInfo', res.loginName)
      store.commit('setId', res.userId)
    }
  }
}
